package com.demo.javase.day65_5;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

/**
 * Properties示例演示
 *
 * @Author bug菌
 * @Date 2023-11-06 16:53
 */
public class PropertiesTest {

    public static void main(String[] args) throws IOException {
        testReadProperties();
        testWriteProperties();
    }

    // 测试读取Properties文件
    public static void testReadProperties() throws IOException {
        Properties props = new Properties();
        InputStream in = new FileInputStream("config/config.properties");
        props.load(new InputStreamReader(in, StandardCharsets.UTF_8));
        in.close();

        String ip = props.getProperty("ip");
        int port = Integer.parseInt(props.getProperty("port"));
        String username = props.getProperty("username");
        String password = props.getProperty("password");

        System.out.println("ip: " + ip);
        System.out.println("port: " + port);
        System.out.println("username: " + username);
        System.out.println("password: " + password);
    }

    // 测试写入Properties文件
    public static void testWriteProperties() throws IOException {
        Properties props = new Properties();
        props.setProperty("ip", "127.0.0.1");
        props.setProperty("port", "8080");
        props.setProperty("username", "admin");
        props.setProperty("password", "123456");

        OutputStream out = new FileOutputStream("config/newConfig.properties");
        props.store(new OutputStreamWriter(out, StandardCharsets.UTF_8), "New Config");
        out.close();
    }
}
